﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;


namespace Ha666.WebAPI
{
    public class TimingActionFilter : ActionFilterAttribute
    {
        private static log4net.ILog Logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        private Stopwatch _time;
        private Stopwatch StopwatchProp
        {
            get { return _time ?? (_time = new Stopwatch()); }
        }
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var token = HttpContext.Current.Request.Form["Token"];
            if (token == null)
                return;
            StopwatchProp.Start();
            actionContext.Request.Properties["token"] = "true";
            if (SkipLogging(actionContext))
                return;
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (!actionExecutedContext.Request.Properties.ContainsKey("token"))
                return;
            var actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
            var controllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            StopwatchProp.Stop();
            string callstring = string.Format("{0}.{1},{2},{3},{4}", controllerName, actionName, DateTime.Now.ToString("yyMMdd"), actionExecutedContext.Response.StatusCode, StopwatchProp.ElapsedMilliseconds);
            StopwatchProp.Reset();
            //new StringList("calls").Add(0, callstring);
            if (StopwatchProp.ElapsedMilliseconds > 20)
            {
                Logger.Error("【TimingActionFilter】超时：" + callstring);
            }
        }

        private static bool SkipLogging(HttpActionContext actionContext)
        {
            return actionContext.ActionDescriptor.GetCustomAttributes<NoLogAttribute>().Any() ||
                    actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<NoLogAttribute>().Any();
        }
    }
    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true)]
    public class NoLogAttribute : Attribute
    {

    }
}